package vip.xianz.jobmanager.util;

import org.springframework.http.HttpRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import vip.xianz.jobmanager.data.entity.XUser;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Session的管理工具类
 *
 * @author xian5
 * @create 2019 -05 -07  16:04
 */
public class SessionUtils {
    public static final String SESSION_USER_KEY = "user";


    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

    public static HttpSession getSession() {
        HttpServletRequest request = getRequest();
        CheckUtils.checkNull(request, "validate.null", "request");
        return request.getSession();
    }

    public static Object getAttribute(String key) {
        HttpSession session = getSession();
        CheckUtils.checkNull(session, "validate.null", "session");
        return session.getAttribute(key);
    }

    public static XUser getUser() {
        return (XUser) getAttribute(SESSION_USER_KEY);
    }
}
